using System;
using System.Collections.Generic;
using System.Text;
using Db4objects.Db4o;
using System.Collections;

namespace SubManager.DAL
{
    /// <summary>
    /// Operation wrapper of db4o.
    /// </summary>
    /// <typeparam name="T">Domain entity in this application.</typeparam>
    public class Db4oHelper<T>
    {
        private static IObjectContainer _db;

        static Db4oHelper()
        {
            _db = Db4oFactory.OpenFile("SubManager.yap");
        }

        public static void Close()
        {
            if (_db != null)
            {
                _db.Close();
            }
        }

        public static void Commit()
        {
            if (_db != null)
            {
                _db.Commit();
            }
        }

        public static void Rollback()
        {
            if (_db != null)
            {
                _db.Rollback();
            }
        }

        /// <summary>
        /// Save entity.
        /// </summary>
        /// <param name="entity">the entity.</param>
        /// <returns></returns>
        public static bool Create(T entity)
        {
            if (_db == null)
                return false;
            try
            {
                _db.Store(entity);
            }
            catch (Exception)
            {
                return false; 
            }
            
            return true;
        }

        public static bool Retrive(T entity)
        {
            if (_db == null)
                return false;
            try
            {
                _db.Activate(entity, 1);
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

        public static bool Update(T entity)
        {
            return true;
        }

        public static bool Delete(T entity)
        {
            if (_db == null)
                return false;
            try
            {
                _db.Delete(entity);
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

        public static List<T> QueryByExample(T entity)
        {
            if (_db == null)
                return null;

            List<T> results = new List<T>();
            try
            {
                IObjectSet set = _db.QueryByExample(entity);
                foreach (T obj in set)
                {
                    results.Add(obj);
                }
            }
            catch (Exception)
            {
                return null;
            }

            return results;
        }


        public static List<T> QueryAll(Type type)
        {
            IList<T> set = _db.Query<T>();
            List<T> entities = new List<T>(set);

            return entities;
        }


    }
}
